package main

import (
	"flag"
	"fmt"
	"image"
	"image/jpeg"
	_ "image/png"
	"os"
	"strings"

	"github.com/sheik/graphics-go/graphics"
)

func main() {
	var w = flag.Int("w", 600, "to this width")
	var q = flag.Int("q", 75, "图片质量(0-100)")
	var o = flag.String("o", "", "输出文件名，默认覆盖原文件")
	flag.Parse()
	img, typ := getImage(flag.Arg(0))
	println(flag.Arg(0))
	if img.Bounds().Max.X > *w {
		//reduce width and height
		img1 := scaleImgTo(img, *w)
		name := flag.Arg(0)
		if *o != "" {
			name = *o
		}
		saveImage(img1, name, *q)
		if typ != "jpeg" {
			//rename
			os.Rename(name, changeExt(name))
		}
	} else {
		fmt.Println("Nothing did.")
	}
	//println(typ)
	//end
}

func changeExt(fn string) string {
	pos := strings.LastIndexByte(fn, '.')
	if pos == -1 {
		return fn
	}
	return fn[0:pos] + ".jpg"
}

func getImage(fn string) (image.Image, string) {
	fp, err := os.Open(fn)
	if err != nil {
		panic(err)
	}
	defer fp.Close()
	img, s, err := image.Decode(fp)
	if err != nil {
		panic(err)
	}
	return img, s
}

func saveImage(img image.Image, fn string, q int) {
	fp, err := os.Create(fn)
	if err != nil {
		panic(err)
	}
	defer fp.Close()
	err = jpeg.Encode(fp, img, &jpeg.Options{Quality: q})
	if err != nil {
		panic(err)
	}
}

func scaleImgTo(img image.Image, w int) image.Image {
	hFloat := float64(img.Bounds().Max.Y) * float64(w) / float64(img.Bounds().Max.X)
	h := int(hFloat)
	var rect = image.Rect(0, 0, w, h)
	ret := image.NewRGBA(rect)
	err := graphics.Scale(ret, img)
	if err != nil {
		panic(err)
	}
	fmt.Printf("scal from [%v,%v] to [%v,%v]\n", img.Bounds().Max.X, img.Bounds().Max.Y, ret.Bounds().Max.X, ret.Bounds().Max.Y)
	return ret
}
